<template>
  <div class="app-container calendar-list-container" style="padding-bottom: 0">
    <div class="apply-query">
      <el-row class="filter-query">
        <el-col><span>{{$t('buBusiness.queryCondition')}}</span></el-col>
      </el-row>
      <el-form :inline="true" :model="listQuery" label-width="120px" style="padding: 10px 20px 0">
        <el-row style="padding-bottom: 10px">

          <el-col :span="4">
            <div class="w20">
              <div class="labelName">{{$t('buWorks.country')}}</div>
              <dict-select v-model="listQuery.country" code="country" :clearable="true" @change="setBg"></dict-select>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="w20">
              <div class="labelName">Category</div>
              <el-select clearable multiple collapse-tags v-model="listQuery.bg" @change="changeBg" :placeholder="$t('placeholder.choose')">
                <el-option v-for="item in bgList" :key="item" :label="item" :value="item"></el-option>
              </el-select>
            </div>
          </el-col>

          <el-col :span="4">
            <div class="w20">
              <div class="labelName">Account</div>
              <el-select clearable multiple collapse-tags class="yt-multiple" v-model="listQuery.bu" @change="changeBu" :placeholder="$t('placeholder.choose')">
                <el-option v-for="item in buList" :key="item" :label="item" :value="item"></el-option>
              </el-select>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="w20">
              <div class="labelName">{{$t('buBusiness.year')}}</div>
              <dict-select v-model="listQuery.year" code="year" clearable></dict-select>
            </div>
          </el-col>
          <el-col :span="6" style="margin-top: 32px">
            <el-button class="yt-btn-ys" type="primary" @click="handleFilter">{{ $t('button.search') }}</el-button>
            <el-button class="yt-btn" type="primary" @click="reset">{{ $t('button.reset') }}</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div v-loading="loading" :element-loading-text="$t('buBusiness.loading')" element-loading-spinner="el-icon-loading">
      <div class="data-list" style="margin-left:-20px;margin-right:-20px;padding-bottom: 0;position: relative">
        <div class="list-content" style="border: none;padding-left: 30px;height: 48px;line-height: 48px"><span style="line-height: 46px">{{$t('buBusiness.buBusinessList')}}</span></div>
        <el-button class="yt-btn-ys" type="primary" style="position: absolute;top:7px;right: 20px" @click="exportExcel">{{$t('button.export')}}</el-button>
      </div>

      <div class="data-list">
        <div class="list-content" style="color: #212121">
          <span style="border: none">{{listQuery.year}} {{ $t('buBusiness.reviewTable') }}</span>&nbsp;<span style="border: none" v-format="'0.0%'">{{reachPercent}}</span>
        </div>
        <el-table :data="businessCheckReach" :empty-text="$t('placeholder.emptyText')" border class="yt-table" style="width: 100%;margin-top: 24px">
          <!--<el-table-column type="index" align="center" :label="$t('buBusiness.index')" width="60"/>-->
          <el-table-column align="center" :label=listQuery.year prop="years" min-width="100"/>
          <el-table-column align="center" label="Q1" prop="q1" min-width="100">
            <template slot-scope="scope">
              <div v-format="scope.row.years === 'Awarded vs Target' ? scope.row.q1 === 0 ? '0%':'0.0%' : '#,##0'">{{ scope.row.q1 }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="Q2" prop="q2" min-width="100">
            <template slot-scope="scope">
              <div v-format="scope.row.years === 'Awarded vs Target' ? scope.row.q2 === 0 ? '0%':'0.0%' : '#,##0'">{{ scope.row.q2 }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="Q3" prop="q3" min-width="100">
            <template slot-scope="scope">
              <div v-format="scope.row.years === 'Awarded vs Target' ? scope.row.q3 === 0 ? '0%':'0.0%' : '#,##0'">{{ scope.row.q3 }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="Q4" prop="q4" min-width="100">
            <template slot-scope="scope">
              <div v-format="scope.row.years === 'Awarded vs Target' ? scope.row.q4 === 0 ? '0%':'0.0%' : '#,##0'">{{ scope.row.q4 }}</div>
            </template>
          </el-table-column>
          <!--<el-table-column align="center" label="May " prop="may" min-width="100">
            <template slot-scope="scope">
              <div v-format="'#,##0'">{{ scope.row.may }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="Jun" prop="jun" min-width="100">
            <template slot-scope="scope">
              <div v-format="'#,##0'">{{ scope.row.jun }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="Jul" prop="jul" min-width="100">
            <template slot-scope="scope">
              <div v-format="'#,##0'">{{ scope.row.jul }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="Aug" prop="aug" min-width="100">
            <template slot-scope="scope">
              <div v-format="'#,##0'">{{ scope.row.aug }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="Sep" prop="sep" min-width="100">
            <template slot-scope="scope">
              <div v-format="'#,##0'">{{ scope.row.sep }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="Oct" prop="oct" min-width="100">
            <template slot-scope="scope">
              <div v-format="'#,##0'">{{ scope.row.oct }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="Nov" prop="nov" min-width="100">
            <template slot-scope="scope">
              <div v-format="'#,##0'">{{ scope.row.nov }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="Dec" prop="dece" min-width="100">
            <template slot-scope="scope">
              <div v-format="'#,##0'">{{ scope.row.dece }}</div>
            </template>
          </el-table-column>-->
          <el-table-column align="center" :label="$t('buBusiness.totalSum')" prop="totalSum" min-width="100">
            <template slot-scope="scope">
              <div v-format="scope.row.years === 'Awarded vs Target' ? scope.row.totalSum === 0 ? '0%':'0.0%' : '#,##0'">{{ scope.row.totalSum }}</div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="data-list">
        <div class="list-content" style="color: #212121">
          <span style="border: none">{{ $t('buBusiness.byStatus') }}( by Status)</span>
        </div>
        <el-table :data="businessCheckStatus" :empty-text="$t('placeholder.emptyText')" border class="yt-table" style="width: 100%;margin-top: 24px">
          <!--<el-table-column type="index" align="center" :label="$t('buBusiness.index')" width="60"/>-->
          <el-table-column align="center" label="Status" prop="status" min-width="100"/>
          <el-table-column align="center" label="Win Odds %" prop="winOddsString" min-width="100"/>
          <el-table-column align="center" label="Awarded" prop="totalSum" min-width="100">
            <template slot-scope="scope">
              <div v-format="'#,##0'">{{ scope.row.totalSum }}</div>
            </template>
          </el-table-column>
         <!-- <el-table-column align="center" label="Actual vs Sales target" prop="actualVsSalesTarget" min-width="100">-->
          <el-table-column align="center" label="%" prop="actualVsSalesTarget" min-width="100">
            <template slot-scope="scope">
              <div v-format="scope.row.actualVsSalesTarget === 0 || scope.row.actualVsSalesTarget % 1 === 0? '0%':'0.0%'">{{ scope.row.actualVsSalesTarget }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="Jan" prop="jan" min-width="100">
            <template slot-scope="scope">
              <div v-format="'#,##0'">{{ scope.row.jan }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="Feb" prop="feb" min-width="100">
            <template slot-scope="scope">
              <div v-format="'#,##0'">{{ scope.row.feb }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="Mar" prop="mar" min-width="100">
            <template slot-scope="scope">
              <div v-format="'#,##0'">{{ scope.row.mar }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="Apr" prop="apr" min-width="100">
            <template slot-scope="scope">
              <div v-format="'#,##0'">{{ scope.row.apr }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="May " prop="may" min-width="100">
            <template slot-scope="scope">
              <div v-format="'#,##0'">{{ scope.row.may }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="Jun" prop="jun" min-width="100">
            <template slot-scope="scope">
              <div v-format="'#,##0'">{{ scope.row.jun }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="Jul" prop="jul" min-width="100">
            <template slot-scope="scope">
              <div v-format="'#,##0'">{{ scope.row.jul }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="Aug" prop="aug" min-width="100">
            <template slot-scope="scope">
              <div v-format="'#,##0'">{{ scope.row.aug }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="Sep" prop="sep" min-width="100">
            <template slot-scope="scope">
              <div v-format="'#,##0'">{{ scope.row.sep }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="Oct" prop="oct" min-width="100">
            <template slot-scope="scope">
              <div v-format="'#,##0'">{{ scope.row.oct }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="Nov" prop="nov" min-width="100">
            <template slot-scope="scope">
              <div v-format="'#,##0'">{{ scope.row.nov }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="Dec" prop="dece" min-width="100">
            <template slot-scope="scope">
              <div v-format="'#,##0'">{{ scope.row.dece }}</div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="data-list">
        <div class="list-content" style="color: #212121">
          <span style="border: none">{{ $t('buBusiness.bySales') }}(by Sales)</span>
        </div>
        <el-table :data="businessCheckSales" :empty-text="$t('placeholder.emptyText')" border class="yt-table" style="width: 100%;margin-top: 24px">
          <!--<el-table-column type="index" align="center" :label="$t('buBusiness.index')" width="60"/>-->
          <el-table-column align="center" label="Sales" prop="sales" min-width="150"/>

          <el-table-column align="center" class-name="pd" label="Sales Target" :show-overflow-tooltip="true" prop="salesTarget" min-width="100">
            <template slot-scope="scope">
              <div v-if="scope.row.sales === '小計'" >
                <div v-format="'#,##0'">{{ scope.row.salesTarget }}</div>
              </div>
              <div v-else-if="scope.row.sales === '累計' || scope.row.sales === '累計%'">
                <div></div>
              </div>
              <div v-else>
                <!--<el-input style="display: none;min-height: 20px" @blur="setActualSalesTarge(scope.$index,scope.row)" type="number" size="small" v-model="scope.row.salesTarget"></el-input>
                <div class="box" v-format="'#,##0'" :placeholder="$t('placeholder.content')">{{ scope.row.salesTarget }}</div>-->
                <div  v-format="'#,##0'">{{ scope.row.salesTarget }}</div>
              </div>
            </template>
          </el-table-column>

          <el-table-column align="center" label="Current Amount" prop="currentAmount" min-width="100">
            <template slot-scope="scope">
              <div v-format="scope.row.sales === '累計%' ? scope.row.currentAmount === 0 ? '0%':'0.0%' : '#,##0'">{{ scope.row.currentAmount }}</div>
            </template>
          </el-table-column>

          <el-table-column align="center" label="Awarded" prop="totalSum" min-width="100">
            <template slot-scope="scope">
              <div v-format="scope.row.sales === '累計%' ? scope.row.totalSum === 0 ? '0%':'0.0%' : '#,##0'">{{ scope.row.totalSum }}</div>
            </template>
          </el-table-column>

          <el-table-column align="center" class-name="pd" label="%" prop="actualSalesTarget" min-width="80">
            <template slot-scope="scope">
              <div v-format=" scope.row.actualSalesTarget === 0 ? '0%':'0.0%'">{{ scope.row.actualSalesTarget }}</div>
            </template>
          </el-table-column>

          <el-table-column align="center" label="Jan" prop="jan" min-width="100">
            <template slot-scope="scope">
              <div v-format="scope.row.sales === '累計%' ? scope.row.jan === 0 ? '0%':'0.0%' : '#,##0'">{{ scope.row.jan }}</div>
            </template>
          </el-table-column>

          <el-table-column align="center" label="Feb" prop="feb" min-width="100">
            <template slot-scope="scope">
              <div v-format="scope.row.sales === '累計%' ? scope.row.feb === 0 ? '0%':'0.0%' : '#,##0'">{{ scope.row.feb }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="Mar" prop="mar" min-width="100">
            <template slot-scope="scope">
              <div v-format="scope.row.sales === '累計%' ? scope.row.mar === 0 ? '0%':'0.0%' : '#,##0'">{{ scope.row.mar }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="Apr" prop="apr" min-width="100">
            <template slot-scope="scope">
              <div v-format="scope.row.sales === '累計%' ? scope.row.apr === 0 ? '0%':'0.0%' : '#,##0'">{{ scope.row.apr }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="May " prop="may" min-width="100">
            <template slot-scope="scope">
              <div v-format="scope.row.sales === '累計%' ? scope.row.may === 0 ? '0%':'0.0%' : '#,##0'">{{ scope.row.may }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="Jun" prop="jun" min-width="100">
            <template slot-scope="scope">
              <div v-format="scope.row.sales === '累計%' ? scope.row.jun === 0 ? '0%':'0.0%' : '#,##0'">{{ scope.row.jun }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="Jul" prop="jul" min-width="100">
            <template slot-scope="scope">
              <div v-format="scope.row.sales === '累計%' ? scope.row.jul === 0 ? '0%':'0.0%' : '#,##0'">{{ scope.row.jul }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="Aug" prop="aug" min-width="100">
            <template slot-scope="scope">
              <div v-format="scope.row.sales === '累計%' ? scope.row.aug === 0 ? '0%':'0.0%' : '#,##0'">{{ scope.row.aug }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="Sep" prop="sep" min-width="100">
            <template slot-scope="scope">
              <div v-format="scope.row.sales === '累計%' ? scope.row.sep === 0 ? '0%':'0.0%' : '#,##0'">{{ scope.row.sep }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="Oct" prop="oct" min-width="100">
            <template slot-scope="scope">
              <div v-format="scope.row.sales === '累計%' ? scope.row.oct === 0 ? '0%':'0.0%' : '#,##0'">{{ scope.row.oct }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="Nov" prop="nov" min-width="100">
            <template slot-scope="scope">
              <div v-format="scope.row.sales === '累計%' ? scope.row.nov === 0 ? '0%':'0.0%' : '#,##0'">{{ scope.row.nov }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="Dec" prop="dece" min-width="100">
            <template slot-scope="scope">
              <div v-format="scope.row.sales === '累計%' ? scope.row.dece === 0 ? '0%':'0.0%' : '#,##0'">{{ scope.row.dece }}</div>
            </template>
          </el-table-column>

        </el-table>
      </div>
    </div>

  </div>
</template>

<script>
  import { getDeptByBuAndCountry } from '@/api/bu/index';
  import { getByHq } from '@/api/worksTarget/index';
  import dictSelect from '@/components/Dict/dictValueSelect';
  import { getBuBusinesscheck, exportBuBusinessCheck } from '@/api/pmoReport/buInspection';
  export default {
    data() {
      return {
        loading: false,
        reachPercent: '', // 达成率
        listQuery: {
          page: 1,
          limit: 10,
          year: '',
          bu: [],
          country: '',
          bg: []
        },
        bgList: [],
        buList: [],
        proportionList: [],
        total: 0,
        businessPlan: [], // Business plan
        actual: [], // Actual
        businessCheckReach: [], // 業務檢視: 目前達成率
        businessCheckStatus: [], // 需求及標案列管( by Status)
        businessCheckSales: [] // 需求及標案列管(by Sales, win odds >61%)
      };
    },
    components: { dictSelect },
    computed: {
      salesTargetSum() {
        let sum = 0
        this.businessCheckSales.forEach(r => {
          sum += Number(!r.salesTarget ? 0 : r.salesTarget)
        })
        return sum
      },
      actualSalesTargetSum() {
        let sum = ''
        const salesTarget = this.salesTargetSum
        let totalSum = 0
        for (let i = 0; i < this.businessCheckSales.length; i++) {
          if (this.businessCheckSales[i].sales === '小計') {
            totalSum = Number(!this.businessCheckSales[i].totalSum ? 0 : this.businessCheckSales[i].totalSum)
            break
          }
        }
        if (salesTarget > 0 && totalSum > 0) {
          sum = this.format(totalSum / salesTarget)
        }
        return sum
      }
    },
    mounted() {
      this.getQuery()
      this.getBg()
      getByHq().then(res => {
        if (res.data.length > 0) {
          this.proportionList = res.data
        }
      })
      if (this.listQuery.year !== '' || this.listQuery.bu.length > 0) {
        this.getList()
      }
    },
    methods: {
      setActualSalesTarge(index, row) {
        const totalSum = Number(!row.totalSum ? 0 : row.totalSum)
        const salesTarget = Number(!row.salesTarget ? 0 : row.salesTarget)

        // 找到小计行index
        let sumIndex = 0;
        let salesTargetCount = 0; // 非小计栏的 salesTarget
        let totalSumCount = 0; // 非小计栏的 totalSum
        for (let i = 0; i < this.businessCheckSales.length; i++) {
          if (this.businessCheckSales[i].sales === '小計') {
            sumIndex = i
            break
          } else {
            salesTargetCount += Number(!this.businessCheckSales[i].salesTarget ? 0 : this.businessCheckSales[i].salesTarget)
            totalSumCount += Number(!this.businessCheckSales[i].totalSum ? 0 : this.businessCheckSales[i].totalSum)
          }
        }

        // 设置对应行的Actual vs Sales Target
        if (salesTarget > 0) {
          this.$set(this.businessCheckSales[index], 'actualSalesTarget', this.format(totalSum / salesTarget))
        } else {
          this.$set(this.businessCheckSales[index], 'actualSalesTarget', '')
        }

        // 设置小计行的salesTarget
        this.$set(this.businessCheckSales[sumIndex], 'salesTarget', salesTargetCount)

        // 设置小计行的Actual vs Sales Target
        let actualSalesTargetSum = ''
        if (salesTargetCount > 0 && totalSumCount > 0) {
          actualSalesTargetSum = this.format(totalSumCount / salesTargetCount)
        }

        this.$set(this.businessCheckSales[sumIndex], 'actualSalesTarget', actualSalesTargetSum)
      },
      format(point) {
        const formated = Number(point * 100).toFixed(1);
        return `${formated}%`
      },
      getQuery() {
        const buBusinessListQuery = window.sessionStorage.getItem('buBusinessListQuery');
        if (buBusinessListQuery) {
          this.listQuery = JSON.parse(buBusinessListQuery);
        }
      },
      reset() {
        this.listQuery = {
          page: 1,
          limit: 10,
          year: '',
          bu: [],
          country: '',
          bg: []
        }
      },
      exportExcel() {
        const obj = {
          userId: this.$store.getters.info.id,
          year: this.listQuery.year,
          businessCheckReach: this.businessCheckReach,
          businessCheckStatus: this.businessCheckStatus,
          businessCheckSales: this.businessCheckSales,
          reachPercent: this.format(this.reachPercent)
        }
        exportBuBusinessCheck(obj).then(res => {
          const blob = new Blob([res], { type: 'application/vnd.ms-excel;charset=utf-8' })
          const downloadElement = document.createElement('a')
          const href = window.URL.createObjectURL(blob) // 创建下载的链接
          downloadElement.href = href
          downloadElement.download = this.$store.state.app.filename // 下载后文件名
          document.body.appendChild(downloadElement)
          downloadElement.click() // 点击下载
          document.body.removeChild(downloadElement) // 下载完成移除元素
          window.URL.revokeObjectURL(href) // 释放掉blob对象
        })
      },
      // exportExcel() {
      //   let str = ''; // 传参数
      //   for (const i in this.listQuery) {
      //     if (this.listQuery[i]) {
      //       str += i + '=' + this.listQuery[i] + '&';
      //     }
      //   }

      //   if (this.$store.getters.info && this.$store.getters.info.id) {
      //     str = str + 'userId=' + this.$store.getters.info.id;
      //   }

      //   const a = document.createElement('a');
      //   const href = '/api/admin/excel/exportBuBusinessCheck?' + str;
      //   a.download = Date.now();
      //   a.href = href;
      //   a.click();
      // },
      handleFilter() {
        this.getList();
      },
      getList() {
        this.loading = true;
        getBuBusinesscheck(this.listQuery).then(res => {
          if (res.status === 201) {
            this.$message.error(res.message);
            this.loading = false
          } else {
            this.businessPlan = res.data.businessPlan
            this.actual = res.data.actual
            this.businessCheckReach = res.data.businessCheckReach
            this.businessCheckStatus = res.data.businessCheckStatus
            this.businessCheckSales = res.data.businessCheckSales
            this.reachPercent = res.data.reachPercent
            this.loading = false
          }
        });
      },
      setBg(country) {
        this.listQuery.bu = []
        this.listQuery.bg = []
        if (country) {
          getDeptByBuAndCountry({ country, bg: this.listQuery.bg, bu: this.listQuery.bu }).then(res => {
            this.bgList = res.data.bgList
            this.buList = res.data.buList
          })
        } else {
          this.getBg()
        }
      },
      getBg() {
        getDeptByBuAndCountry({ country: '', bg: [], bu: [] }).then(res => {
          if (res) {
            this.buList = res.data.buList
            this.bgList = res.data.bgList
          }
        })
      },
      changeBg(row) {
        if (row.length === 0) {
          this.listQuery.bg = []
        }
        getDeptByBuAndCountry({ country: this.listQuery.country, bg: row, bu: [] }).then(res => {
          this.buList = res.data.buList
        })
      },
      changeBu(row) {
        if (row.length === 0) {
          this.listQuery.bg = []
        }
        getDeptByBuAndCountry({ country: this.listQuery.country, bg: this.listQuery.bg, bu: [] }).then(res => {
          this.bgList = res.data.bgList
        })
      }
    },
    beforeDestroy() {
      window.sessionStorage.setItem('buBusinessListQuery', JSON.stringify(this.listQuery))
    }
  };
</script>
<style scoped lang="scss">

  .box{
    //padding: 0 15px !important;
    height: 13px;
    line-height: 13px;
    text-align: center;
    border-radius: 4px;
    color: #333;
  }

  .box:empty:before{
    content: attr(placeholder);
    color: #c0c4cc;
    font-size: 14px;
  }
</style>
